package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet(urlPatterns = "/download")
public class DownloadServlet extends HttpServlet {

    private static final String UPLOAD_DIRECTORY = "uploads";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求中的文件名参数
        String fileName = req.getParameter("fileName");
        String filePath1="D:/upload/images"+fileName;
        if (fileName == null || fileName.isEmpty()) {
            resp.getWriter().println("文件名参数缺失！");
            return;
        }

        // 获取文件在服务器上的路径
        String filePath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY + File.separator + fileName;
        File downloadFile = new File(filePath);

        if (!downloadFile.exists()) {
            resp.getWriter().println("文件不存在！");
            return;
        }

        // 设置响应内容类型
        resp.setContentType("application/octet-stream");
        resp.setContentLength((int) downloadFile.length());
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

        // 使用输入输出流传输文件
        /**
         * 下载关键代码！！！
         */
        try (FileInputStream inStream = new FileInputStream(downloadFile);
             OutputStream outStream = resp.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
        }
    }
}
